package com.frog.service.friend.service.relation;


import com.alibaba.fastjson.JSON;
import com.frog.service.friend.common.CommonStringUtil;
import com.frog.service.friend.mapper.FriendImportantMessageDOMapper;
import com.frog.service.friend.model.RelationModel;
import com.frog.service.friend.model.domain.FriendFollowingRelationshipDO;
import com.frog.service.friend.model.domain.FriendImportantMessageDO;
import com.frog.service.friend.service.cache.BestFriendedService;
import com.frog.service.friend.service.cache.FriendFollowService;
import com.frog.service.friend.service.friendList.MaintainRelationService;
import com.frog.service.friend.utils.FriendRelationshipUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


/**
 * bestfriend好友关系实例
 */
@Slf4j
@Service("bestFriendRelationInstance")
public class BestRelation implements Relation {

    @Autowired
    private FriendFollowService friendFollowService;
    @Autowired
    private BestFriendedService bestInvitedService;
    @Autowired
    private FriendImportantMessageDOMapper friendImportantMessageDOMapper;
    @Autowired
    private MaintainRelationService maintainRelationService;

    /**
     * 添加bestfriend好友关系
     *
     * @param userId       主动发起人
     * @param friendUserId 被动添加人
     * @return 添加完成后状态
     */
    @Override
    public boolean establish(Integer userId, Integer friendUserId) {
        Long id = FriendRelationshipUtil.processRelationId(userId, friendUserId);
        if (id == null || id == 0) return false;
        FriendFollowingRelationshipDO f = friendFollowService.select(String.valueOf(id));
        boolean havePermissionsAddBest = bestInvitedService.havePermissionsAddBest(userId, f);
        if (!havePermissionsAddBest) return false;
        return f == null ? initAddBest(id, userId, friendUserId) : renewAddBest(id, userId, friendUserId, f);
    }


    /**
     * 解除bestfriend好友关系
     *
     * @param userId       主动发起人
     * @param friendUserId 被动解除关系人
     * @return 解除关系后状态
     */
    @Override
    public boolean termination(Integer userId, Integer friendUserId) {
        Long id = FriendRelationshipUtil.processRelationId(userId, friendUserId);
        if (id == null || id == 0) return false;
        FriendFollowingRelationshipDO f = friendFollowService.select(String.valueOf(id));
        return renewCancelBest(id, userId, friendUserId, f);
    }


    /**
     * 关注best好友,初始化best好友关系
     */
    private boolean initAddBest(Long id, Integer userId, Integer friendUserId) {
        long time = System.currentTimeMillis();
        // 添加好友关系表和缓存
        FriendFollowingRelationshipDO f = FriendFollowingRelationshipDO.builder().id(id)
                .fromUserId(userId)
                .toUserId(friendUserId)
                .followStatus(CommonStringUtil.FriendBothStatus.notConcerned)
                .bestStatus(CommonStringUtil.FriendBothStatus.sendConcerned)
                .blockStatus(CommonStringUtil.FriendBothStatus.notConcerned)
                .cancelStatus(CommonStringUtil.FriendBothStatus.notConcerned)
                .bestTime(time)
                .createTime(time)
                .updateTime(time)
                .build();
        if (!friendFollowService.save(id, f)) return false;

        // 保存friendList
        RelationModel r = new RelationModel(id, userId, userId, friendUserId, CommonStringUtil.FriendBothStatus.notConcerned, true);
        maintainRelationService.addBestfriend(r);

        // 添加好友记录信息表
        FriendImportantMessageDO im = FriendImportantMessageDO.builder()
                .fromUserId(userId)
                .toUserId(friendUserId)
                .messageType(CommonStringUtil.FriendBothStatus.notConcerned)
                .createTime(time)
                .build();
        Integer status = 0;
        try {
            status = friendImportantMessageDOMapper.insertData(im);
        } catch (Exception exception) {
            log.error("initAddBest friendImportantMessageDOMapper exception: id=={} im=={} ", id, JSON.toJSONString(im), exception);
        }
        return status != 0;
    }


    /**
     * 更新添加bestfriend好友关系
     */
    private boolean renewAddBest(Long id, Integer userId, Integer friendUserId, FriendFollowingRelationshipDO f) {
        if (f == null) return false;
        if (userId == null || friendUserId == null) return false;
        // 将要修改成的目标好友关系状态值
        Integer fromUserId = f.getFromUserId();
        Integer toUserId = f.getToUserId();
        RelationModel r = new RelationModel(id, userId, fromUserId, toUserId, f.getBestStatus(), true);
        if (!r.isSuccessStatus()) return false;

        // 更新bestfriend关系
        long time = System.currentTimeMillis();
        Map<String, Object> fieldMap = new HashMap<>();
        fieldMap.put("best_status", r.getStatusLater());
        fieldMap.put("best_time", time);
        fieldMap.put("update_time", time);
        if (!friendFollowService.modify(id, fieldMap)) return false;

        // 更新关系成功后,更新friendList
        maintainRelationService.addBestfriend(r);

        // 修改记录添加数据库
        FriendImportantMessageDO im = FriendImportantMessageDO.builder()
                .fromUserId(userId).toUserId(friendUserId)
                .createTime(time)
                .messageType(CommonStringUtil.FriendBothStatus.notConcerned)
                .build();
        Integer status = 0;
        try {
            status = friendImportantMessageDOMapper.insertData(im);
        } catch (Exception e) {
            log.error("renewAddBest friendImportantMessageDOMapper exception: id=={} im=={} ", id, JSON.toJSONString(im), e);
        }
        return status != 0;
    }


    /**
     * 更新解除bestfriend好友关系
     */
    private boolean renewCancelBest(Long id, Integer userId, Integer friendUserId, FriendFollowingRelationshipDO f) {
        if (f == null) return false;
        if (userId == null || friendUserId == null) return false;
        // 将要修改成的目标好友关系状态值
        Integer fromUserId = f.getFromUserId();
        Integer toUserId = f.getToUserId();
        RelationModel r = new RelationModel(id, userId, fromUserId, toUserId, f.getBestStatus(), false);
        if (!r.isSuccessStatus()) return false;

        // 更新bestfriend关系
        long time = System.currentTimeMillis();
        Map<String, Object> fm = new HashMap<>();
        fm.put("best_status", r.getStatusLater());
        fm.put("best_time", time);
        fm.put("update_time", time);
        if (!friendFollowService.modify(id, fm)) return false;

        // 更新关系成功后,更新friendList
        maintainRelationService.delBestfriend(r);
        return true;
    }


}